<template>
	<view class="container">
		<button class="alarm-btn" type="default" @click="addAlarmFrame">添加闹钟提醒</button>

		<view class="alarm-list">
			<view v-for="(alarm, alarmIndex) in alarms" :key="alarmIndex" class="alarm-item">
				<view class="alarm-info" @click="openDatetimePicker(alarmIndex)">
					<text class="alarm-time">闹钟时间：{{ alarm.time }}</text>
				</view>
				<view class="alarm-info">
					<picker @change="onRepeatChange($event, alarmIndex)" :value="alarm.repeatIndex"
						:range="repeatOptions" range-key="name">
						<view style="margin-top: 20rpx;">重复：{{ alarm.repeatText }}</view>
					</picker>
				</view>
				<view v-if="alarm.isCustomRepeat">
					<text style="margin-top: 20rpx;">设置自定义重复</text>
					<checkbox-group @change="onCustomRepeatChange($event, alarmIndex)">
						<label v-for="(day, index) in days" :key="index">
							<checkbox :value="day.name" :checked="alarm.selectedDays.includes(day.code)">{{ day.name }}
							</checkbox>
						</label>
					</checkbox-group>
				</view>
				<view class="alarm-info">
					<picker mode="selector" :range="remarkOptions" @change="onRemarkChange($event, alarmIndex)"
						:value="alarm.remarkIndex">
						<view style="margin-top: 20rpx;">备注：{{ alarm.remarkText }}</view>
					</picker>
				</view>
				<view class="alarm-info">
					<button @click="saveAlarm(alarmIndex)" class="save-button">发送</button>
					<button @click="deleteAlarm(alarmIndex)" class="delete-button">删除</button>
				</view>
			</view>
		</view>

		<buuug7-simple-datetime-picker ref="myPicker" @submit="handleSubmit" :time-hide="[true, true]"
			:time-label="[ '时', '分']" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				alarms: [],
				currentAlarmIndex: null,
				repeatOptions: [{
						name: '只响一次',
						code: 'once'
					},
					{
						name: '每天',
						code: 'daily'
					},
					{
						name: '自定义',
						code: 'custom'
					}
				],
				days: [{
						name: '星期一',
						code: 'Monday'
					},
					{
						name: '星期二',
						code: 'Tuesday'
					},
					{
						name: '星期三',
						code: 'Wednesday'
					},
					{
						name: '星期四',
						code: 'Thursday'
					},
					{
						name: '星期五',
						code: 'Friday'
					},
					{
						name: '星期六',
						code: 'Saturday'
					},
					{
						name: '星期日',
						code: 'Sunday'
					}
				],
				remarkOptions: ['报警', '其他', '喝水', '吃饭', '吃药', '大便', '小便', '闹钟'],
				deviceUUID: null
			}
		},
		onLoad(options) {
			if (options.uuid) {
				console.log('闹钟页面收到uuid', options.uuid);
				this.deviceUUID = options.uuid;
			} else {
				console.log('wifi页面没有收到uuid')
			}
			this.loadAlarms();
		},
		methods: {
			loadAlarms() {
				// 从本地存储或服务器获取已有的闹钟数据
				const storedAlarms = uni.getStorageSync('alarms') || [];
				console.log('加载闹钟', storedAlarms); // 添加日志
				// 根据uuid筛选出对应设备的闹钟
				this.alarms = storedAlarms.filter(alarm => alarm.deviceUUID === this.deviceUUID);
			},
			addAlarmFrame() {
				const newAlarm = {
					time: '请选择时间',
					repeatIndex: 0,
					repeatText: '只响一次',
					isCustomRepeat: false,
					selectedDays: [],
					remarkIndex: 0,
					remarkText: '报警',
					deviceUUID: this.deviceUUID // 添加设备UUID
				};
				this.alarms.push(newAlarm);
				console.log('添加闹钟', this.alarms); // 添加日志
			},
			openDatetimePicker(index) {
				this.currentAlarmIndex = index;
				const now = new Date();
				this.$refs.myPicker.show({
					timeInit: now.getTime()
				});
			},
			handleSubmit(e) {
				const formattedTime = `${e.hour}:${e.minute}`;
				this.$set(this.alarms[this.currentAlarmIndex], 'time', formattedTime);
				this.$refs.myPicker.hide();
			},
			onRepeatChange(e, alarmIndex) {
				const repeatIndex = e.detail.value;
				this.$set(this.alarms[alarmIndex], 'repeatIndex', repeatIndex);
				this.$set(this.alarms[alarmIndex], 'isCustomRepeat', this.repeatOptions[repeatIndex].name === '自定义');
				this.$set(this.alarms[alarmIndex], 'repeatText', this.repeatOptions[repeatIndex].name);
			},
			onCustomRepeatChange(e, alarmIndex) {
				const selectedDays = e.detail.value;
				this.$set(this.alarms[alarmIndex], 'selectedDays', selectedDays);
			},
			onRemarkChange(e, alarmIndex) {
				const remarkIndex = e.detail.value;
				this.$set(this.alarms[alarmIndex], 'remarkIndex', remarkIndex);
				this.$set(this.alarms[alarmIndex], 'remarkText', this.remarkOptions[remarkIndex]);
			},
			getRemarkCode(remarkText) {
				const remarkCodes = {
					'报警': "1",
					'其他': "2",
					'喝水': "3",
					'吃饭': "4",
					'吃药': "5",
					'大便': "6",
					'小便': "7",
					'闹钟': "8"
				};
				return remarkCodes[remarkText] || 0;
			},
			saveAlarm(alarmIndex) {
				const alarm = this.alarms[alarmIndex];
				const repeatOption = this.repeatOptions[alarm.repeatIndex];
				const selectedDays = alarm.selectedDays.map(day => this.days.find(d => d.name === day).code);
				const remarkCode = this.getRemarkCode(alarm.remarkText);

				if (alarm.isCustomRepeat && alarm.selectedDays.length > 0) {
					alarm.repeatText = `自定义 (${alarm.selectedDays.join(', ')})`;
				} else {
					alarm.repeatText = repeatOption.name;
				}
				this.$set(this.alarms, alarmIndex, alarm);
				this.$set(this.alarms[alarmIndex], 'isCustomRepeat', false);
				uni.showToast({
					title: '发送闹钟成功',
					icon: 'success',
					duration: 2000
				});
				// 通过MQTT发布消息
				this.publishAlarmToDevice({
					time: alarm.time,
					repeat: repeatOption.code,
					selectedDays: selectedDays,
					code: remarkCode
				});
				// 将闹钟数据存储到本地存储
				let storedAlarms = uni.getStorageSync('alarms') || [];
				storedAlarms = storedAlarms.filter(alarm => alarm.deviceUUID !== this.deviceUUID);
				storedAlarms = storedAlarms.concat(this.alarms);
				uni.setStorageSync('alarms', storedAlarms);
				console.log('保存闹钟', this.alarms);
			},
			deleteAlarm(alarmIndex) {
				console.log('删除前闹钟列表', this.alarms); // 添加日志
				this.alarms.splice(alarmIndex, 1);

				// 更新本地存储中的闹钟数据
				let storedAlarms = uni.getStorageSync('alarms') || [];
				storedAlarms = storedAlarms.filter(alarm => alarm.deviceUUID !== this.deviceUUID);
				storedAlarms = storedAlarms.concat(this.alarms);
				uni.setStorageSync('alarms', storedAlarms);
				console.log('删除后闹钟列表', this.alarms); // 添加日志
			},
			publishAlarmToDevice(alarm) {
				const message = {
					msg: "alarm_config",
					data: {
						time: alarm.time,
						repeat: alarm.repeat,
						selectedDays: alarm.selectedDays,
						code: alarm.code
					}
				};
				const opts = {
					topic: `LSY/app/${this.deviceUUID}`,
					message: JSON.stringify(message)
				};
				this.$mqttTool.publish(opts).then(res => {
					console.log('MQTT消息发送成功', res);
				}).catch(err => {
					console.error('MQTT消息发送失败', err);
				});
			}
		},
	}
</script>

<style>
	.setting-section {
		margin-top: 20px;
	}

	.alarm-list {
		margin-top: 20px;
	}

	.alarm-item {
		background-color: #f9f9f9;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		margin-bottom: 10px;
	}

	.alarm-info {
		margin: 10rpx;
		cursor: pointer;
	}

	.alarm-time,
	.alarm-repeat {
		white-space: pre-wrap;
		word-wrap: break-word;
	}

	.save-button,
	.reset-button,
	.delete-button {
		margin-top: 20rpx;
		font-size: 12px;
		padding: 5px 10px;
		margin-right: 5px;
		border: none;
		border-radius: 3px;
	}

	.save-button {
		background-color: green;
		color: white;
	}

	.delete-button {
		background-color: red;
		color: white;
	}

	.alarm-btn {
		margin: 20rpx;
	}
</style>